import axios from 'axios'
import {
  refreshToken
} from './apis'
import {
  Message
} from 'element-ui'
// 导入nprogress包和对应的js和css
import NProgress from 'nprogress'
// 转到 index文件中由cdn引入
// import 'nprogress/nprogress.css'
const newAxios = axios.create({
  // baseURL: 'http://127.0.0.1:5000/api/',
  baseURL: 'https://api.thunderup.cn/api/',
  timeout: 5000
})
// 是否正在刷新token
let isRefreshing = false
newAxios.interceptors.request.use(config => {
  // 显示进度条
  NProgress.start()
  let token = ''
  if (config.url === 'refresh') {
    token = window.localStorage.getItem('refresh_token')
  } else {
    token = window.localStorage.getItem('access_token')
  }
  config.headers.Authorization = 'Bearer ' + token
  return config
})
// 请求队列
let requests = []
newAxios.interceptors.response.use(response => {
  // 隐藏进度条
  NProgress.done()
  const meta = response.data.meta
  if (meta.status === 403) {
    const config = response.config
    if (!isRefreshing) {
      isRefreshing = true
      return refreshToken().then(res => {
        const data = res.data
        window.localStorage.setItem('access_token', data.access_token)
        requests.forEach(cb => {
          cb()
        })
        requests = []
        return newAxios(config)
      }).catch(res => {
        Message({
          type: 'error',
          message: '请重新登录',
          duration: 1500,
          onClose: () => {
            window.location.href = '/'
          }
        })
      }).finally(() => {
        isRefreshing = false
      })
    } else {
      return new Promise((resolve) => {
        requests.push(() => {
          resolve(newAxios(config))
        })
      })
    }
  }
  if (meta.status === 401) {
    window.localStorage.removeItem('access_token')
    window.localStorage.removeItem('refresh_token')
    window.location.href = '/'
  }
  // if (!meta.status.toString().slice(0, 1) === '2') {
  //   Message.error(meta.msg)
  // }
  return response.data
})

export default newAxios
